package com.ngc.mall.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ngc.mall.common.configure.LocalUser;
import com.ngc.mall.common.configure.mybatisPlus.BaseServiceImpl;
import com.ngc.mall.core.enumeration.PlatformType;
import com.ngc.mall.domain.WxUserDomain;
import com.ngc.mall.dto.WxUserDTO;
import com.ngc.mall.mapper.WxUserMapper;
import com.ngc.mall.service.IUserIntegralService;
import com.ngc.mall.service.IWxAuthenticationService;
import com.ngc.mall.util.CommonUtil;
import com.ngc.mall.util.JwtToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 *  微信生成/校验token
 *
 * @author : Chen Xiao Lin
 * @Date : 2023/3/20 15:10
 **/
@Service
public class WxAuthenticationServiceImpl extends BaseServiceImpl<WxUserMapper,WxUserDomain> implements IWxAuthenticationService {
    @Autowired
    private ObjectMapper mapper;

    @Value("${wechat.user.code2session}")
    private String code2SessionUrl;

    @Value("${wechat.user.appid}")
    private String appid;

    @Value("${wechat.user.secret}")
    private String secret;

    @Autowired
    private IUserIntegralService iUserIntegralService;

    /**
     * code换取session_key,openid
     * @param code
     * @return
     */
    @Override
    public String code2Session(String code){
        String url = MessageFormat.format(this.code2SessionUrl, this.appid, this.secret, code);
        RestTemplate rest = new RestTemplate();
        Map<String, Object> session = new HashMap<>();
        String sessionText = rest.getForObject(url, String.class);
        try {
            session = mapper.readValue(sessionText, Map.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
       return this.registerUser(session);
    }

    /**
     * 更新微信用户信息
     * @param wxUserDTO
     * @return
     */
    @Override
    public Boolean updateUserWxInfo(WxUserDTO wxUserDTO) {
        return super.update(Wrappers.<WxUserDomain>lambdaUpdate()
                .eq(WxUserDomain::getId,LocalUser.getUser().getId())
                .set(WxUserDomain::getNickname,wxUserDTO.getNickname())
                .set(WxUserDomain::getProfilePhoto,wxUserDTO.getAvatarUrl())
        );
    }

    @Override
    public WxUserDomain getUserById(Long uid) {
        return super.getById(uid);
    }

    /**
     * 注册新用户
     * @param session
     * @return
     */
    private String registerUser(Map<String,Object> session){
        String openid = (String) session.get("openid");
        if (openid == null){
            System.out.println("openid is null");;
        }
            Optional<WxUserDomain> wxUserDomainOptional = Optional.ofNullable(super.getOne(Wrappers.<WxUserDomain>lambdaQuery()
                    .eq(WxUserDomain::getOpenid, openid)));
        if(wxUserDomainOptional.isPresent()){
            // TODO:返回JWT令牌
            // 数字等级
            return JwtToken.makeToken(wxUserDomainOptional.get().getId());
        }
        String nickname= CommonUtil.generateByRandom(6);
        ///注册即为普通会员
        WxUserDomain user = WxUserDomain.builder()
                .nickname(nickname)
                .source(PlatformType.MINI_PROGRAM.getValue())
                .levelId((long) 1)
                .openid(openid)
                .build();
        //        // TODO:返回JWT令牌
        Long uid=super.create(user);
        iUserIntegralService.create(uid);
        return JwtToken.makeToken(uid);
    }


}
